package com.example.mydb;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class DatabaseManager {

    private static DatabaseManager sInstance;
    private SQLiteDatabase mDatabase;
    private DatabaseHelper mDatabaseHelper;

    private DatabaseManager(Context context) {
        mDatabaseHelper = new DatabaseHelper(context);
        mDatabase = mDatabaseHelper.getWritableDatabase();
    }

    public static synchronized DatabaseManager getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new DatabaseManager(context.getApplicationContext());
        }
        return sInstance;
    }

    public void insertData(String name) {
        ContentValues values = new ContentValues();
        values.put("name", name);
        mDatabase.insert("mytable", null, values);
    }

    public List<String> queryData() {
        List<String> data = new ArrayList<>();
        Cursor cursor = mDatabase.rawQuery("SELECT name FROM mytable", null);
        if (cursor.moveToFirst()) {
            do {
                data.add(cursor.getString(cursor.getColumnIndexOrThrow("name")));
            } while (cursor.moveToNext());
        }
        cursor.close();
        return data;
    }

    public void updateData(String name, String newName) {
        ContentValues values = new ContentValues();
        values.put("name", newName);
        mDatabase.update("mytable", values, "name=?", new String[]{name});
    }

    public void deleteData(String name) {
        mDatabase.delete("mytable", "name=?", new String[]{name});
    }
}